package site.jlopen.controller.api;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import site.jlopen.assets.config.ThreadAuthUser;
import site.jlopen.assets.oss.AwsOssConfig;
import site.jlopen.domain.datasource.KusciaDatasource;
import site.jlopen.domain.datasource.KusciaDatasourceNode;
import site.jlopen.domain.datasource.KusciaDatasourceOss;
import site.jlopen.domain.datasource.event.KusciaDatasourceEvent;
import site.jlopen.domain.datasource.event.KusciaDatasourceOssEvent;
import site.jlopen.domain.node.event.KusciaNodeEvent;
import site.jlopen.entity.BaseResponse;
import site.jlopen.entity.req.DatasourceReq;
import site.jlopen.mapper.datasource.KusciaDatasourceMapper;
import site.jlopen.mapper.datasource.KusciaDatasourceNodeMapper;
import site.jlopen.mapper.datasource.KusciaDatasourceOssMapper;
import site.jlopen.secret.model.data.SecretDatasourceCreateReq;
import site.jlopen.secret.model.data.SecretDatasourceInfoResp;
import site.jlopen.service.BaseService;
import site.jlopen.service.intf.oss.OssService;
import site.jlopen.utils.StringUtil;
import site.jlopen.utils.id.IdUtils;

@RestController
@RequestMapping(value="/api/datasource")
public class ApiDatasourceController extends BaseService {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private OssService ossService;
	@Autowired
	private KusciaDatasourceOssMapper ossMapper;
	@Autowired
	private KusciaDatasourceMapper dataSourceMapper;
	@Autowired
	private KusciaDatasourceNodeMapper dataSourceNodeMapper;
	
	@PostMapping(value = "/create" )
	public BaseResponse<String> create(@RequestBody SecretDatasourceCreateReq form) {
		logger.info("数据源接口调用");
		if(form.getPrefix().startsWith("/") || form.getPrefix().endsWith("/")) {
			return new BaseResponse<String>().error("前缀属性前后不能出现/字符");
		}
		KusciaDatasourceEvent info = dataSourceService.getDataSource(ThreadAuthUser.id(), form.getCode());
		if(null != info) {
			return new BaseResponse<String>().error("该编号的数据源已存在");
		}
		/*Long nodeId = null;
		if(StringUtil.isNotBlank(form.getNodeCode())) {
			KusciaNodeEvent node = nodeService.getNodeByCode(ThreadAuthUser.id(), form.getNodeCode());
			if(null == node) {
				return new BaseResponse<String>().error("该节点编号不存在");
			}
			nodeId = node.getNodeId();
		}*/
		Long dsId= IdUtils.SnowFlakeId();
		try {
			BaseResponse<String> ossRes = ossService.checkBucketExists(AwsOssConfig.builder().endpoint(form.getEndpoint()).accessKeyId(form.getAccessKey())
					.secretAccessKey(form.getAccessSecret()).build(), form.getBucket());
			if(ossRes.getStatus() != 0) {
				return ossRes;
			}
			KusciaDatasourceOss ossInfo = new KusciaDatasourceOss().setOssId(IdUtils.SnowFlakeId()).setOssDatasourceId(dsId)
					.setOssEndpoint(form.getEndpoint()).setOssBucket(form.getBucket()).setOssPrefix(form.getPrefix())
					.setOssAccessKeyId(form.getAccessKey()).setOssAccessKeySecret(form.getAccessSecret())
					.setOssVirtualhost(form.getVirtualhost()).setOssVersion(null)
					.setOssStorageType(null).setOssCreate(new Date());
			ossMapper.insertSelective(ossInfo);
			KusciaDatasource dsInfo = new KusciaDatasource().setDatasourceId(dsId).setDatasourceUserId(ThreadAuthUser.id())
					.setDatasourceName(form.getName()).setDatasourceCode(form.getCode())
					.setDatasourceType(form.getType()).setDatasourceInfoKey(null).setDatasourceAccessDirectly(1)
					.setDatasourceCreate(new Date());
			dataSourceMapper.insertSelective(dsInfo);
			/*if(null != nodeId) {
				dataSourceNodeMapper.insertSelective(new KusciaDatasourceNode()
						.setDnId(IdUtils.SnowFlakeId())
						.setDnDatasourceId(dsId)
						.setDnNodeId(nodeId)
						.setDnStatus(0)
						.setDnCreate(new Date())
						);
			}*/
			return new BaseResponse<String>().success("保存成功");
		} catch (Exception e) {
			logger.error("保存接口数据源数据异常：{}", e);
			return new BaseResponse<String>().error("保存失败");
		}
	} 
	
	@PostMapping(value = "/update" )
	public BaseResponse<String> update(@RequestBody SecretDatasourceCreateReq form) {
		DatasourceReq req = new DatasourceReq();
		return dataSourceService.updateDataSource(req);
	}
	
	@PostMapping(value = "/remove" )
	public BaseResponse<String> remove(String datasourceCode) {
		KusciaDatasourceEvent info = dataSourceService.getDataSource(ThreadAuthUser.id(), datasourceCode);
		if(null == info) {
			return new BaseResponse<String>().error("该编号的数据源不存在");
		}
		return dataSourceService.remove(info.getDatasourceId());
	}
	
	@PostMapping(value = "/bind" )
	public BaseResponse<String> bind(String datasourceCode, String nodeCode) {
		KusciaDatasourceEvent info = dataSourceService.getDataSource(ThreadAuthUser.id(), datasourceCode);
		if(null == info) {
			return new BaseResponse<String>().error("该编号的数据源不存在");
		}
		KusciaNodeEvent node = nodeService.getNodeByCode(ThreadAuthUser.id(), nodeCode);
		if(null == node) {
			return new BaseResponse<String>().error("该节点编号不存在");
		}
		return dataSourceService.bindNode(info.getDatasourceId(), node.getNodeId());
	}
	
	@PostMapping(value = "/unbind" )
	public BaseResponse<String> unbind(String datasourceCode, String nodeCode) {
		KusciaDatasourceEvent info = dataSourceService.getDataSource(ThreadAuthUser.id(), datasourceCode);
		if(null == info) {
			return new BaseResponse<String>().error("该编号的数据源不存在");
		}
		KusciaNodeEvent node = nodeService.getNodeByCode(ThreadAuthUser.id(), nodeCode);
		if(null == node) {
			return new BaseResponse<String>().error("该节点编号不存在");
		}
		return dataSourceService.unBindNode(info.getDatasourceId(), node.getNodeId());
	}
	
	@PostMapping(value = "/status" )
	public BaseResponse<String> datasourceStatus(String datasourceCode, String nodeCode) {
		KusciaDatasourceEvent info = dataSourceService.getDataSource(ThreadAuthUser.id(), datasourceCode);
		if(null == info) {
			return new BaseResponse<String>().error("该编号的数据源不存在");
		}
		KusciaNodeEvent node = nodeService.getNodeByCode(ThreadAuthUser.id(), nodeCode);
		if(null == node) {
			return new BaseResponse<String>().error("该节点编号不存在");
		}
		return dataSourceService.restatus(info.getDatasourceId(), node.getNodeId());
	}
	
	@PostMapping(value = "/info" )
	public BaseResponse<SecretDatasourceInfoResp> datasourceInfo(String datasourceCode) {
		KusciaDatasourceEvent info = dataSourceService.getDataSource(ThreadAuthUser.id(), datasourceCode);
		if(null == info) {
			return new BaseResponse<SecretDatasourceInfoResp>().error("该编号的数据源不存在");
		}
		KusciaDatasourceOssEvent ossinfo = dataSourceService.getDatasourceOss(info.getDatasourceId());
		if(null == ossinfo) {
			return new BaseResponse<SecretDatasourceInfoResp>().error("暂无数据源记录");
		}
		SecretDatasourceInfoResp resp = new SecretDatasourceInfoResp();
		resp.setType(info.getDatasourceType());
		resp.setName(info.getDatasourceName());
		resp.setCode(info.getDatasourceCode());
		
		SecretDatasourceInfoResp.SecretDatasourceOss oss = resp.new SecretDatasourceOss();
		oss.setEndpoint(ossinfo.getOssEndpoint());
		oss.setBucket(ossinfo.getOssBucket());
		oss.setAccessKeyId(ossinfo.getOssAccessKeyId());
		oss.setAccessKeySecret(ossinfo.getOssAccessKeySecret());
		oss.setPrefix(ossinfo.getOssPrefix());
		oss.setStorageType(ossinfo.getOssStorageType());
		oss.setVirtualhost(ossinfo.getOssVirtualhost());
		oss.setVersion(ossinfo.getOssVersion());
		resp.setOss(oss);
		return new BaseResponse<SecretDatasourceInfoResp>().success("成功").setData(resp);
	}
}